/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora.client.mvp;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ResizeComposite;
import redora.client.util.Field;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * A widget displaying attributes of an object. You can shuffle or change these
 * fields before invoking the init method.
 * @author Nanjing RedOrange (www.red-orange.cn)
 */
public abstract class FieldedComposite extends Composite implements FieldView {
    protected final ArrayList<Field> fields = new ArrayList<Field>();

    public void moveField(int from, int to) {
        Field[] sorted = new Field[fields.size()];
        for (int i = 0; i < fields.size(); i++) {
            int p = i;
            if (i > to) p = i + 1; //after the 'to' is added the sorted queue is +1 larger
            if (i > from) p = i - 1; //after the 'from' is removed, subtract 1 from the queue
            if (i != from && i != to) {
                sorted[p] = fields.get(i);
            } else if (i == to) {
                sorted[p] = fields.get(from);
                sorted[p + 1] = fields.get(i);
            }
        }
        fields.clear();
        fields.addAll(Arrays.asList(sorted));
    }

    /**
     * Fields used to display with this view.
     */
    public ArrayList<Field> fields() {
        return fields;
    }
}
